package com.cd.javacxy.module.web.service.impl;

import cn.hutool.core.util.StrUtil;
import com.cd.javacxy.common.model.entity.CxyAttachment;
import com.cd.javacxy.common.model.entity.CxyKnowledge;
import com.cd.javacxy.common.model.enums.*;
import com.cd.javacxy.common.model.query.KnowledgeQuery;
import com.cd.javacxy.common.model.query.MessageParams;
import com.cd.javacxy.common.model.query.UpdateQuery4ArticleCount;
import com.cd.javacxy.common.utils.CxyUtils;
import com.cd.javacxy.common.utils.ImageUtils;
import com.cd.javacxy.common.utils.Page;
import com.cd.javacxy.common.utils.PageResult;
import com.cd.javacxy.exception.BussinessException;
import com.cd.javacxy.module.web.dao.CxyKnowledgeDao;
import com.cd.javacxy.module.web.service.CxyAttachmentService;
import com.cd.javacxy.module.web.service.CxyKnowledgeService;
import com.cd.javacxy.module.web.service.CxyMessageService;
import com.cd.javacxy.module.web.service.CxyUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * CxyKnowledge的服务接口的实现类
 *
 * @author yanghy
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CxyKnowledgeServiceImpl implements CxyKnowledgeService {

    private final CxyKnowledgeDao knowledgeDao;
    private final CxyAttachmentService attachmentService;
    private final FormateAtService formateAtService;
    private final CxyUserService cxyUserService;
    private final CxyMessageService cxyMessageService;

    @Override
    public PageResult<CxyKnowledge> findKnowledgeByPage(KnowledgeQuery knowledgeQuery) {
        knowledgeQuery.setStatus(StatusEnum.AUDIT);
        int count = this.knowledgeDao.selectCount(knowledgeQuery);
        int pageSize = PageSize.PAGE_SIZE20.getSize();
        int pageNum = knowledgeQuery.getPageNum();
        Page page = new Page(pageNum, count, pageSize);
        knowledgeQuery.setPage(page);
        knowledgeQuery.setOrderBy(OrderByEnum.CREATE_TIME_DESC);
        List<CxyKnowledge> list = this.knowledgeDao.selectList(knowledgeQuery);
        return new PageResult<>(page, list);
    }

    @Override
    public CxyKnowledge showKnowledge(Integer knowledgeId, Integer userId) throws BussinessException {
        CxyKnowledge knowledge = this.getKnowledge(knowledgeId);
       /* Set<Integer> roleSet = sysRoleService.findRoleIdsByUserId(userId);
        List<CxySysRes> list = sysResService.findMenuByRoleIds(roleSet);
        Set<String> permkey = new HashSet<>();
        if (list != null) {
            for (SysRes sysRes : list) {
                permkey.add(sysRes.getKey());
            }
        } || permkey == null || !permkey.contains("content:knowledge:review")
        */
        if (knowledge == null || (knowledge.getStatus() == StatusEnum.INIT && knowledge.getUserId().intValue() != userId)) {
            throw new BussinessException("文章不存在,或已删除");
        }
        knowledge.setAttachment(this.attachmentService.getAttachmentByTopicIdAndFileType(knowledge.getTopicId(), FileTopicType.KNOWLEDGE));
        UpdateQuery4ArticleCount updateQuery4ArticleCount = new UpdateQuery4ArticleCount();
        updateQuery4ArticleCount.setAddReadCount(Boolean.TRUE);
        updateQuery4ArticleCount.setArticleId(knowledgeId);
        this.knowledgeDao.updateInfoCount(updateQuery4ArticleCount);
        return knowledge;
    }


    public CxyKnowledge getKnowledge(Integer knowledgeId) {
        if (knowledgeId == null) {
            return null;
        }
        KnowledgeQuery knowledgeQuery = new KnowledgeQuery();
        knowledgeQuery.setTopicId(knowledgeId);
        knowledgeQuery.setShowContent(Boolean.TRUE);
        List<CxyKnowledge> list = this.knowledgeDao.selectList(knowledgeQuery);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = BussinessException.class)
    public int addKnowledge(CxyKnowledge knowledge, CxyAttachment attachment) throws BussinessException {
        if (knowledge.getTitle() == null || knowledge.getTitle().length() > TextLengthEnum.TEXT_300_LENGTH.getLength()
                || knowledge.getPCategoryId() == null || knowledge.getCategoryId() == null ||
                StrUtil.isEmpty(knowledge.getContent()) || knowledge.getContent().length() > TextLengthEnum.LONGTEXT.getLength()
        ) {
            throw new BussinessException("参数错误");
        }
        String title = HtmlUtils.htmlUnescape(knowledge.getTitle());
        String content = knowledge.getContent();
        String summary = CxyUtils.cleanHtmlTag(HtmlUtils.htmlUnescape(content));
        if (summary.length() > TextLengthEnum.TEXT_200_LENGTH.getLength()) {
            summary = summary.substring(0,
                    (int) TextLengthEnum.TEXT_200_LENGTH.getLength())
                    + "......";
        }
        Set<Integer> userIds = new HashSet<Integer>();
        //TODO给用户发消息
        String formatContent = formateAtService.generateRefererLinks(content,
                userIds);
        knowledge.setSummary(summary);
        knowledge.setTitle(title);
        knowledge.setContent(formatContent);
        String topicImage = ImageUtils.getImages(content);
        knowledge.setTopicImage(topicImage);
//		String knowledgeImageSmall = ImageUtils.createThumbnail(topicImage, true);
//		knowledge.setTopicImageThum(knowledgeImageSmall);
        LocalDateTime curDate = LocalDateTime.now();
        knowledge.setCreateTime(curDate);
        knowledge.setLastCommentTime(curDate);
        knowledge.setStatus(StatusEnum.INIT);
        this.knowledgeDao.insert(knowledge);
        this.cxyUserService.changeMark(knowledge.getUserId(),
                MarkEnum.MARK_TOPIC.getMark());

        if (!StrUtil.isEmpty(attachment.getFileName()) &&
                !StrUtil.isEmpty(attachment.getFileUrl())) {
            attachment.setTopicId(knowledge.getTopicId());
            attachment.setTopicType(FileTopicType.KNOWLEDGE);
            this.attachmentService.addAttachment(attachment);
        }

        MessageParams messageParams = new MessageParams();
        messageParams.setArticleId(knowledge.getTopicId());
        messageParams.setArticleType(ArticleType.KNOWLEDGE);
        messageParams.setArticleUserId(knowledge.getUserId());
        messageParams.setMessageType(MessageType.AT_ARTICLE_MESSAGE);
        messageParams.setSendUserName(knowledge.getUserName());
        messageParams.setSendUserId(knowledge.getUserId());
        messageParams.setReceiveUserIds(userIds);
        cxyMessageService.createMessage(messageParams);
        return 0;
    }

    @Override
    public List<CxyKnowledge> findKnowledgeList() {
        KnowledgeQuery knowledgeQuery = new KnowledgeQuery();
        knowledgeQuery.setStatus(StatusEnum.INIT);
        knowledgeQuery.setOrderBy(OrderByEnum.CREATE_TIME_DESC);
        return knowledgeDao.selectList(knowledgeQuery);
    }

    @Override
    public int deleteBatch(Integer[] ids) throws BussinessException {
        if (ids == null) {
            throw new BussinessException("参数错误");
        }
        for (int id : ids) {
            knowledgeDao.delete(id);
        }
        return 0;
    }

    @Override
    public int updateStatusBatch(Integer[] ids) throws BussinessException {
        if (ids == null) {
            throw new BussinessException("参数错误");
        }
        knowledgeDao.updateKnowledgeStatus(StatusEnum.AUDIT, ids);
        return 0;
    }
}